using POC.Common;
using Unity.Collections;
using Unity.Entities;
using Unity.Mathematics;
using Unity.NetCode;
using Unity.Transforms;
using UnityEngine;

namespace POC.Server
{
    [WorldSystemFilter(WorldSystemFilterFlags.ServerSimulation)]                //只运行在服务端
    public partial struct ServerProcessGameEntryRequestSystem : ISystem
    {
        public void OnCreate(ref SystemState state)
        {
            //SendRpcCommandRequest组件在服务端就被转换成了ReceiveRpcCommandRequest组件
            var builder = new EntityQueryBuilder(Allocator.Temp).WithAll<MobaTeamRequest, ReceiveRpcCommandRequest>();
            state.RequireForUpdate(state.GetEntityQuery(builder));
        }

        public void OnUpdate(ref SystemState state)
        {
            var entityCommandBuffer = new EntityCommandBuffer(Allocator.Temp);
            var championPrefab = SystemAPI.GetSingleton<MobaPrefabs>().Champion;
            foreach (var (teamRequest, requestSource, requestEntity) in SystemAPI.Query<MobaTeamRequest, ReceiveRpcCommandRequest>().WithEntityAccess())
            {
                //处理了就销毁这个Entity，避免多次处理同一个
                entityCommandBuffer.DestroyEntity(requestEntity);
                //添加一个NetworkStreamInGame组件
                entityCommandBuffer.AddComponent<NetworkStreamInGame>(requestSource.SourceConnection);
                //获取队伍
                var requestedTeamType = teamRequest.Value;
                if (requestedTeamType == TeamType.AutoAssign)
                {
                    requestedTeamType = TeamType.Blue;
                }

                var clientId = SystemAPI.GetComponent<NetworkId>(requestSource.SourceConnection).Value;
                Debug.Log($"Server is assigning Client ID: {clientId} to the {requestedTeamType.ToString()} Team");

                //客户端连接成功，服务端给创建实例
                var newChampion = entityCommandBuffer.Instantiate(championPrefab);
                entityCommandBuffer.SetName(newChampion, "Champion");
                //根据队伍设置玩家生成的位置
                float3 spawnPosition;
                switch (requestedTeamType)
                {
                    case TeamType.Blue:
                        spawnPosition = new float3(-50f, 1f, -50f);
                        break;
                    case TeamType.Red:
                        spawnPosition = new float3(50f, 1f, 50f);
                        break;
                    default:
                        continue;
                }
                
                var newTransform = LocalTransform.FromPosition(spawnPosition);
                entityCommandBuffer.SetComponent(newChampion, newTransform);
                entityCommandBuffer.SetComponent(newChampion, new GhostOwner { NetworkId = clientId });
                entityCommandBuffer.SetComponent(newChampion, new MobaTeam { Value = requestedTeamType });
                
                entityCommandBuffer.AppendToBuffer(requestSource.SourceConnection, new LinkedEntityGroup { Value = newChampion });
            }
            entityCommandBuffer.Playback(state.EntityManager);
        }
    }
}